package com.zx.web.service.impl;

import com.zx.bean.Order;
import com.zx.bean.User;
import com.zx.utils.DataSourceUtils;
import com.zx.web.dao.AdminUserDao;
import com.zx.web.dao.impl.AdminUserDaoImpl;
import com.zx.web.service.AdminUserService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.web.service.impl
 * @Description:
 * @Date 2022/9/16 9:42
 */
public class AdminUserServiceImpl implements AdminUserService {

    AdminUserDao adminUserDao = new AdminUserDaoImpl();

    @Override
    public User findAdmin(String username, String password) {
        User admin = adminUserDao.findAdmin(username,password);
        if(admin!=null){
            if (admin.getRole()==1) {
                return admin;
            }
        }
        return null;
    }

    @Override
    public List<User> findAllValid() {
        return adminUserDao.findAllValid();
    }

    @Override
    public void deleteUser(int id) {
        Connection connection = null;
        try {
            connection = DataSourceUtils.getConnection();
            connection.setAutoCommit(false);
            //根据uid查询order表，使用id先删orderdetail
            List<Order> orderList = adminUserDao.findOrder(id);
            for (Order order : orderList) {
                adminUserDao.deleteOrderDetail(order.getId());
            }
            //根据uid再删order表
            adminUserDao.deleteOrder(id);

            //根据id（uid）删cart表
            adminUserDao.deleteCart(id);

            //根据uid删address表
            adminUserDao.deleteAddress(id);

            //最后删除user表
            adminUserDao.deleteUser(id);
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } finally {
        }
    }

    @Override
    public List<User> findUserList(String username, String gender) {
        return adminUserDao.findUserList(username,gender);
    }

    @Override
    public List<User> findAllInValid() {
        return adminUserDao.findAllInValid();
    }
}
